package com.care.inquiry.server.im.handler;

import com.alibaba.fastjson2.JSON;

import com.alibaba.fastjson2.JSONException;
import com.care.inquiry.server.im.Command;
import com.care.inquiry.server.im.CommandType;
import com.care.inquiry.server.im.Result;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

/**
 * @version: java version 1.8
 * @author: cuiweijie
 * @date: 2024-03-25 19:09
 */
public class WebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame frame) throws Exception {

        //这样netty的客户端和服务端就建立还连接
        try {
            //将客户端发送的消息打印
            System.out.println(frame.text());
            String text = frame.text();
            Command command = JSON.parseObject(text, Command.class);
            switch (CommandType.match(command.getCode())){
                case CONNECTION:
                    ConnectionHandler.execute(ctx,command);
                    break;
                case CHAT:
                    ChatHandler.execute(ctx,frame);
                    break;
                default:
                    ctx.channel().writeAndFlush(Result.fail("不支持的CODE"));
                    break;
            }
        } catch (JSONException e) { // 使用更具体的异常类型
            ctx.channel().writeAndFlush(Result.fail("解析JSON时发生异常: " + e.getMessage()));
        } catch (Exception e) {
            ctx.channel().writeAndFlush(Result.fail("发生异常: " + e.getMessage()));
        }


    }
}
